﻿"""
本脚本仅在某服务器刚装完Ubuntu24后，初次启用时调用
mkdir tmp_for_start_docker_nginx && \
    git clone https://gitee.com/children1987/start_docker_nginx_ubuntu.git tmp_for_start_docker_nginx/t && \
    python3 ./tmp_for_start_docker_nginx/t/start_nginx_docker_setuped.py
"""

import os
import shutil
import subprocess


def cmd(cmd_str):
    print(f"执行命令: {cmd_str}")
    if subprocess.call(cmd_str, shell=True) != 0:
        raise Exception(f"{cmd_str} 执行失败")


def main():
    # 确保以root权限运行
    if os.geteuid() != 0:
        raise Exception("请以root权限运行")

    # 如果不存在daemon.json则移动并重启docker服务
    if not os.path.exists('/etc/docker/daemon.json'):
        shutil.move('./tmp_for_start_docker_nginx/t/daemon.json', '/etc/docker')
        cmd('sudo systemctl restart docker')

    # 创建Nginx日志目录
    nginx_log_path = '/workspace/nginx/log'
    os.makedirs(nginx_log_path, exist_ok=True)

    # 将nginx配置文件移动到适当的位置
    nginx_path = '/workspace/nginx/'
    shutil.move('./tmp_for_start_docker_nginx/t/nginx_base.conf', nginx_path)
    shutil.move('./tmp_for_start_docker_nginx/t/uwsgi_params', nginx_path)

    # 运行Docker容器
    cmd('docker run --name nginx --restart always --network host -d -v /workspace/nginx/nginx_base.conf:/etc/nginx/nginx.conf -v /workspace:/workspace nginx:1.27.2-alpine')

    # 清理临时文件夹
    print("清理 tmp_for_start_docker_nginx 开始")
    shutil.rmtree('./tmp_for_start_docker_nginx', ignore_errors=True)
    print("清理 tmp_for_start_docker_nginx 完成")


if __name__ == '__main__':
    main()
